package handler

import (
	"fmt"
	"ideatools/application/db/dbdto"
	"ideatools/application/db/dbservice"
	"ideatools/application/pkgs/mylog"
	"math"
	"strings"
	"time"
)

// 流式返回---面板
func (s *HandlerMessageService) gptSendByStream() {
	FormatChatContents := GetDoalogChatContents(s.CurrChatUserContent.ChatDialogId)
	if len(FormatChatContents) > 1 {
		FormatChatContents = FormatChatContents[:len(FormatChatContents)-1]
	}

	//设置gpt配置
	SetGptConfig(s.HandlerStream)

	// 调用GptService的GetText方法获取文本
	s.StreamSendLastTime = time.Now()
	s.StreamSendStartTime = time.Now()
	_, err := GptService.SendContents(FormatChatContents)
	if err != nil {
		mylog.Error("gptSendByStream" + err.Error())
	}
}

// HandlerStream 处理回调
func (s *HandlerMessageService) HandlerStream(text string, isEnd bool, isError bool) {
	if isEnd {
		s.IsHandingTask = false
		errInfo := ""
		if isError {
			errInfo = text
		}
		err := dbservice.ChatDialog().UpdateAiRespond(
			s.CurrChatAiContent.ID,
			&dbdto.ChatContentUpdate{
				Content:   s.CurrChatAiContent.Content,
				IsHanding: false,
				IsError:   isError,
				ErrorMsg:  errInfo,
				UseTime:   GetUseTime(s.StreamSendStartTime),
			})
		if err != nil {
			mylog.Error(err.Error())
			return
		}

		aiContent := dbservice.ChatDialog().GetContentInfoById(s.CurrChatAiContent.ID)
		s.CurrChatAiContent = aiContent
		NotifyFrontMessageContent(s.CurrChatAiContent, nil)
	} else {

		s.CurrChatAiContent.Content += text
		s.CurrChatAiContent.IsHanding = false

		// 计算两个时间的毫秒差值
		duration := time.Now().Sub(s.StreamSendLastTime)
		milliseconds := duration.Milliseconds()
		if milliseconds > StreamSendSpaceTime && strings.TrimSpace(s.CurrChatAiContent.Content) != "" {
			s.StreamSendLastTime = time.Now()
			//时间间隔达到 则发送
			NotifyFrontMessageContent(s.CurrChatAiContent, nil)
		} else {
			mylog.Debug(fmt.Sprintf("%v", milliseconds))
		}
	}

}

func GetUseTime(startTime time.Time) float64 {

	useTime := time.Now().Sub(startTime) // 计算使用时间
	// 将useTime转换为秒，并保留两位小数
	useTimeSeconds := useTime.Seconds()
	useTimeFloat := math.Round(useTimeSeconds*100) / 100

	return useTimeFloat
}
